/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.web.filters;

import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.tianyun.cloud.utils.JsonUtils;

import javax.servlet.Filter;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * 抽象的过滤器，所有过滤器的父类
 *
 * @auther ebert_chan
 */
public abstract class AbstractFilter implements Filter, Ordered {

    /**
     * 高优先级Filter，通常系统框架使用
     */
    public static final int HIGHEST_PRECEDENCE_FILTER = 0;

    /**
     * 低优先级Filter，应用内自定义Filter
     */
    public static final int LOWEST_PRECEDENCE_FILTER = 100;

    /**
     * servlet-context-filter
     */
    protected static final int FILTER_SERVLET_CONTEXT_ORDERED = HIGHEST_PRECEDENCE_FILTER + 1;

    /**
     * exception-filter
     */
    protected static final int FILTER_EXCEPTION_ORDERED = HIGHEST_PRECEDENCE_FILTER + 2;

    /**
     * 响应json数据
     *
     * @param result
     * @param response
     * @auther ebert_chan
     */
    public void responseJson(Object result, ServletResponse response) {
        PrintWriter writer = null;
        String json = JsonUtils.toJsonString(result);
        try {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            writer = response.getWriter();
            writer.print(json);
            writer.flush();
        } catch (Throwable e) {
            // do nothing
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
